<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Lives;
use Carbon\Carbon;
use Illuminate\Http\Request;

class LiveController extends Controller {

    public function index(Request $request){
        $params = [
            'kwd'  => (string)$request->get('title',''),
            'status'  => (int)$request->get('status',0),
            'position'  => (int)$request->get('position',0),
            'start'  => (string)$request->get('start',''),
            'end'  => (string)$request->get('end',''),
        ];
        $lists = Lives::where(function ($query) use ($params) {
                if($params['kwd']) $query ->where('content','like','%' . $params['kwd'] . '%');
                if($params['status']) $query ->where('status',$params['status']);
                if($params['position']) $query ->where('position',$params['position']);
                if($params['start']) $query ->whereDate('created_at','>=',$params['start']);
                if($params['end']) $query ->whereDate('created_at','<=',$params['end']);
            })->orderBy('created_at', 'desc')
            ->paginate(10);
        $this->stateToText($lists,[
            'status' => Lives::STATUS_TEXT,
            'position' => Lives::POSITION_TEXT,
        ]);
        return $this->writeJson(0,$lists);
    }

    //更新
    public function update(Request $request)
    {
        $data = $request->all();
        if($data['id']){
            $info = Lives::findOrFail($data['id']);
            $info->update($data);
            return $this->writeJson(0,null,'修改快讯信息成功');
        }else{
            unset($data['id']);
            switch (Carbon::now()->dayOfWeek){
                case 1:
                    $data['week'] = '星期一';
                    break;
                case 2:
                    $data['week'] = '星期二';
                    break;
                case 3:
                    $data['week'] = '星期三';
                    break;
                case 4:
                    $data['week'] = '星期四';
                    break;
                case 5:
                    $data['week'] = '星期五';
                    break;
                case 6:
                    $data['week'] = '星期六';
                    break;
                default:
                    $data['week'] = '星期日';
                    break;
            }
            Lives::create($data);
            return $this->writeJson(0,null,'新增快讯信息成功');
        }
    }

    //删除
    public function destroy(Request $request){
        $id = $request->get('id');
        if(empty($id)){
            return $this->writeJson(1,null,'参数错误');
        }
        if(is_array($id)){
            Lives::whereIn('id',$id)->delete();
        }else{
            Lives::destroy($id);
        }
        return $this->writeJson(0);
    }

}
